package com.scisoft.scan.ws;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scisoft.scan.data.BarCodeBean;
import com.scisoft.scan.data.MenuItemBean;
import com.scisoft.scan.data.UpdateVersionInfo;
import com.scisoft.scan.dy.UserInfo;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.util.ArrayList;
import java.util.List;

public class WebServiceHelper {

    public static String GetWS_Url() {
        return String.format("http://%s/dymps/ws/LoginService?wsdl", SysParameter.WS_IPandPort);
    }

    public static String WS_Method = "receive";

    public static String WS_Namespace = "http://login.scan.ws.dms.com/";

    //查询最新版本信息，检查客户端app是否需要升级
    public static UpdateVersionInfo GetUpdateVersion(String localVersion) throws Exception {
        //return UpdateVersionInfo.getDefaultData();
        //可以复用以前的方法
        String arg0 = String.format("{\"flowNo\":\"LOGIN_01\",\"localVersion\":\"%s\",\"jsonData\":{},\"scSequence\":\"%s\"}", localVersion, SysParameter.ScSequence);
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        UpdateVersionInfo ret = new UpdateVersionInfo();
        if (msg != null && msg.contains("成功")) {
            JSONObject jsonArray = data.getJSONObject("jsonData");
            Gson gson = new Gson();
            ret = gson.fromJson(jsonArray.toString(), new TypeToken<UpdateVersionInfo>() {
            }.getType());
        } else {
            throw new Exception(msg);
        }
        return ret;
    }

    //用户登录
    public static String Login(String account, String password) throws Exception {
        //return "成功";
        //可以复用以前的方法
        String arg0 = String.format("{\"flowNo\":\"LOGIN_02\",\"account\":\"%s\",\"jsonData\":{},\"password\":\"%s\",\"scSequence\":\"%s\"}", account, password, SysParameter.ScSequence);
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        return msg;
    }

    /*单点登录的方法
          1、在Login时记录account的设备id。
          2、app每隔1分钟会调用AccountCheck，进行心跳轮询检查，需要传递参数为：账号和设备id。
          3、在AccountCheck时，如果账号和设备id与最后登录的一致,返回 1 那么app继续进行；如果不一致返回0，app强制退回到登录界面。
         */
    //账号单点登录判断 1 表示app当前登录正常 0 表示app登录异常，需要退回到登录界面
    public static UserInfo AccountCheck() throws Exception {
//        UserInfo ret = new UserInfo();
//        ret.userId = "1";
//        ret.userName = "张三";
//        ret.isValidate = "1";//有效账号，登录成功
//        return ret;

        //可以复用以前的方法，把返回值改一下，改为返回用户账号信息
        String arg0 = String.format("{\"flowNo\":\"LOGIN_03\",\"account\":\"%s\",\"jsonData\":{},\"scSequence\":\"%s\"}", SysParameter.user, SysParameter.ScSequence);
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        UserInfo ret = new UserInfo();
        if (msg != null && msg.contains("成功")) {
            JSONObject jsonArray = data.getJSONObject("jsonData");
            Gson gson = new Gson();
            ret = gson.fromJson(jsonArray.toString(), new TypeToken<UserInfo>() {
            }.getType());
        } else {
            throw new Exception(msg);
        }
        return ret;

    }

    //获取用户可见的菜单列表
    public static List<MenuItemBean> GetUserVisibleMenu(String account, String password) throws Exception {
        //return MenuItemBean.getAllMenuItemList();

        String arg0 = String.format("{\"flowNo\":\"LOGIN_04\",\"account\":\"%s\",\"scSequence\":\"%s\",\"bizId\":\"%s\"}", SysParameter.user, SysParameter.ScSequence, "");
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        List<MenuItemBean> ret = new ArrayList<>();
        if (msg != null && msg.contains("成功")) {
            Gson gson = new Gson();
            JSONArray jsonArray = data.getJSONArray("jsonData");
            ret = gson.fromJson(jsonArray.toString(), new TypeToken<List<MenuItemBean>>() {
            }.getType());
        } else {
            throw new Exception(msg);
        }
        return ret;

    }

    //上传客户端的异常闪退信息
    public static String LogException(String crashInfo) throws Exception {
        String arg0 = String.format("{\"flowNo\":\"LOGIN_05\",\"account\":\"%s\",\"jsonData\":{},\"password\":\"%s\",\"scSequence\":\"%s\",\"bizId\":\"%s\"}", SysParameter.user, SysParameter.password, SysParameter.ScSequence, crashInfo);
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        String ret = "成功";
        if (msg != null && msg.contains("成功")) {

        } else {
            throw new Exception(msg);
        }
        return ret;
    }

    /*
     *  条码解析服务
     *  1、根据条码查询后台数据库，判断是配件还是货架。
     *  2、如果是配件则把返回结果的配件字段赋值，并把barType设置为BAR_PART（1）
     *  3、如果是货架则把返回结果的货架字段赋值，并把barType设置为BAR_SHELVES（2）
     *  4、如果是无效则把返回结果的barType设置为BAR_UNKNOWN（0）
     */
    public static BarCodeBean ParseBarCode(String barCode) throws Exception {
        String arg0 = String.format("{\"flowNo\":\"SCAN_01\",\"account\":\"%s\",\"jsonData\":{},\"scSequence\":\"%s\",\"bizId\":\"%s\"}", SysParameter.user, SysParameter.ScSequence, barCode);
        SoapObject soapObject = CallWebservice(arg0);
        // 解析json
        String json = soapObject.getProperty(0).toString();
        JSONObject data = new JSONObject(json);
        String msg = data.optString("mESSAGE");
        BarCodeBean ret = new BarCodeBean();
        if (msg != null && msg.contains("成功")) {
            JSONObject jsonArray = data.getJSONObject("jsonData");
            Gson gson = new Gson();
            ret = gson.fromJson(jsonArray.toString(), new TypeToken<BarCodeBean>() {
            }.getType());
        } else {
            throw new Exception(msg);
        }
        //return ret;
       /* //测试数据
        if (barCode.equals("12-0495-CH")) {
            barCodeBean.barType = BarCodeBean.BAR_PART;//配件
            barCodeBean.partBean.supplierCode = "DY001";
            barCodeBean.partBean.partNo = "P001";
            barCodeBean.partBean.partCode = "P001";
            barCodeBean.partBean.partCount = "1";
            barCodeBean.partBean.serialNo = "ABCD";
        } else {
            barCodeBean.barType = BarCodeBean.BAR_SHELVES;//货架
            barCodeBean.shelvesBean.shelvesName = "D01";
        }*/
        return ret;
    }

    public static SoapObject CallWebservice(String arg0) throws Exception {
        SoapObject result = null;
        try {
            //实例化SoapObject对象：命名空间+方法名称
            SoapObject request = new SoapObject(WS_Namespace, WS_Method);
            //设置WebService接口需要传入的参数
            request.addProperty("arg0", arg0);

            //创建SoapSerializationEnvelope 对象，同时指定soap版本号
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
            envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
            envelope.dotNet = false;//由于是.net开发的webservice，所以这里要设置为true

            //调用接口
            ArrayList<HeaderProperty> headerPropertyArrayList = new ArrayList<HeaderProperty>();
            headerPropertyArrayList.add(new HeaderProperty("Connection", "close"));
            HttpTransportSE httpTransportSE = new HttpTransportSE(GetWS_Url());
            httpTransportSE.call(null, envelope, headerPropertyArrayList);//调用

            // 获取返回的数据
            if (envelope.bodyIn instanceof SoapFault) {
                String msg = ((SoapFault) envelope.bodyIn).faultstring;
                throw new Exception(msg);
            } else {
                result = (SoapObject) envelope.bodyIn;
            }
            result = (SoapObject) envelope.bodyIn;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }
}
